package cbfg.http.util

import android.os.Handler
import android.os.HandlerThread
import android.os.Looper
import cbfg.http.constant.ThreadMode
import java.util.concurrent.ExecutorService
import java.util.concurrent.SynchronousQueue
import java.util.concurrent.ThreadPoolExecutor
import java.util.concurrent.TimeUnit

object ThreadUtils {
    /**
     * @param mode
     * ThreadMode.MAIN：在主线程中执行 --- 回调时的默认线程( 非网络请求 )
     * ThreadMode.BACKGROUND：IO 线程执行 --- 串行模式，只有一条子线程
     * ThreadMode.ASYNC：异步执行，每次都会新起一个线程
     */
    fun run(mode: ThreadMode, runnable: Runnable) {
        when (mode) {
            ThreadMode.MAIN -> UIThreadHolder.INSTANCE.post(runnable)
            ThreadMode.BACKGROUND -> IOThreadHolder.INSTANCE.post(runnable)
            ThreadMode.ASYNC -> {
                if (!AsyncThreadHolder.cacheExecutor.isShutdown) {
                    AsyncThreadHolder.cacheExecutor.execute(runnable)
                }
            }
        }
    }

    private object UIThreadHolder {
        var INSTANCE = Handler(Looper.getMainLooper())
    }

    private object IOThreadHolder {
        val handlerThread: HandlerThread by lazy {
            HandlerThread("IOHandlerThread").also { it.start() }
        }
        val INSTANCE = Handler(handlerThread.looper)
    }

    private object AsyncThreadHolder {
        val cacheExecutor: ExecutorService = ThreadPoolExecutor(
            0, Int.MAX_VALUE,  //最大线程数
            60L,  //保活时间
            TimeUnit.SECONDS,  //单位
            SynchronousQueue()
        )
    }
}